package com.zz.common

import scala.concurrent.{ExecutionContext, Future}

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.stream.Materializer
import cats.effect.IO
import com.zz.common.cassandra.{CassandraConfig, CassandraExtension}
import com.zz.idl.{IdMappingSimpleService, IdMappingSimpleServiceHandler, SimpleZid, ZidIndex}

class IdMappingSimpleServiceImpl()(implicit system: ActorSystem, ec: ExecutionContext) extends IdMappingSimpleService {
  val storage = new ZidScyllaStorage(CassandraExtension(system).cassandra)
  override def put(in: ZidIndex): Future[SimpleZid] = {
    storage.storeIdBundleWithoutZid(in).map(SimpleZid(_))
  }
}

object IdMappingSimpleService {
  def run(host: String, port: Int)(implicit system: ActorSystem, mat: Materializer, ec: ExecutionContext): IO[Http.ServerBinding] =
    IO.fromFuture(IO {
      val service = IdMappingSimpleServiceHandler(new IdMappingSimpleServiceImpl)
      val binding = Http().bindAndHandleAsync(service, host, port)
      binding
    })(IO.contextShift(ec))
}
